﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace OrderManagementSystem
{
    // 为了支持 XML 序列化，给 OrderDetails 和 Order 类加上必要的特性
    [XmlRoot("Order")]
    public class OrderDetails
    {
        [XmlElement("GoodsName")]
        public string GoodsName { get; set; }

        [XmlElement("UnitPrice")]
        public decimal UnitPrice { get; set; }

        [XmlElement("Quantity")]
        public int Quantity { get; set; }

        public override bool Equals(object obj)
        {
            return obj is OrderDetails details &&
                   GoodsName == details.GoodsName &&
                   UnitPrice == details.UnitPrice &&
                   Quantity == details.Quantity;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(GoodsName, UnitPrice, Quantity);
        }

        public override string ToString()
        {
            return $"{GoodsName} (单价：{UnitPrice:C}，数量：{Quantity})";
        }
    }

    [XmlRoot("OrderList")]
    public class Order
    {
        [XmlElement("OrderId")]
        public string OrderId { get; set; }

        [XmlElement("Customer")]
        public string Customer { get; set; }

        [XmlArray("OrderDetails")]
        [XmlArrayItem("Detail")]
        public List<OrderDetails> Details { get; } = new List<OrderDetails>();

        [XmlIgnore]
        public decimal TotalAmount => Details.Sum(d => d.UnitPrice * d.Quantity);

        public override bool Equals(object obj)
        {
            return obj is Order order &&
                   OrderId == order.OrderId;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(OrderId);
        }

        public override string ToString()
        {
            return $"订单号：{OrderId}\n客户：{Customer}\n总金额：{TotalAmount:C}\n明细：\n{string.Join("\n", Details)}";
        }
    }

    public class OrderService
    {
        private List<Order> orders = new List<Order>();

        // Add Order, Remove Order, Update Order, etc...

        // 导出订单为 XML 文件
        public void Export(string filePath)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(List<Order>));
                using (var writer = new StreamWriter(filePath))
                {
                    serializer.Serialize(writer, orders);
                }
                Console.WriteLine("订单导出成功！");
            }
            catch (Exception e)
            {
                Console.WriteLine($"导出失败：{e.Message}");
            }
        }

        // 从 XML 文件导入订单
        public void Import(string filePath)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(List<Order>));
                using (var reader = new StreamReader(filePath))
                {
                    orders = (List<Order>)serializer.Deserialize(reader);
                }
                Console.WriteLine("订单导入成功！");
            }
            catch (Exception e)
            {
                Console.WriteLine($"导入失败：{e.Message}");
            }
        }

        // 使用LINQ实现查询
        public IEnumerable<Order> QueryOrders(Func<Order, bool> predicate = null, Comparison<Order> sortComparison = null)
        {
            var query = orders.AsEnumerable();

            if (predicate != null)
                query = query.Where(predicate);

            return sortComparison != null
                ? query.OrderBy(o => o, new ComparisonComparer<Order>(sortComparison))
                : query.OrderBy(o => o.TotalAmount);
        }

        // 排序方法
        public void SortOrders(Comparison<Order> comparison = null)
        {
            if (comparison == null)
                orders.Sort((a, b) => a.OrderId.CompareTo(b.OrderId));
            else
                orders.Sort(comparison);
        }

        // 自定义比较器
        private class ComparisonComparer<T> : IComparer<T>
        {
            private readonly Comparison<T> comparison;
            public ComparisonComparer(Comparison<T> comparison) => this.comparison = comparison;
            public int Compare(T x, T y) => comparison(x, y);
        }
    }

    class Program
    {
        static OrderService service = new OrderService();

        static void Main()
        {
            while (true)
            {
                Console.WriteLine("\n1. 添加订单\n2. 删除订单\n3. 修改订单\n4. 查询订单\n5. 导出订单\n6. 导入订单\n7. 退出");
                Console.Write("请选择操作：");
                switch (Console.ReadLine())
                {
                    case "1": AddOrder(); break;
                    case "2": RemoveOrder(); break;
                    case "3": UpdateOrder(); break;
                    case "4": QueryOrders(); break;
                    case "5": ExportOrders(); break;
                    case "6": ImportOrders(); break;
                    case "7": return;
                }
            }
        }

        static void AddOrder()
        {
            // Add order implementation
        }

        static void RemoveOrder()
        {
            // Remove order implementation
        }

        static void QueryOrders()
        {
            // Query orders implementation
        }

        static void UpdateOrder()
        {
            // Update order implementation
        }

        static void ExportOrders()
        {
            Console.Write("请输入导出的文件路径：");
            var filePath = Console.ReadLine();
            service.Export(filePath);
        }

        static void ImportOrders()
        {
            Console.Write("请输入导入的文件路径：");
            var filePath = Console.ReadLine();
            service.Import(filePath);
        }
    }
}
